package com.fy56.platform.logistics.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.mapper.DeliverGoodsWebSetMapper;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.DeliverGoodsWeb;
import com.fy56.platform.logistics.service.wx.IDeliverGoodsWebSetService;
import com.fy56.platform.logistics.utils.HttpClientUtils;
import com.fy56.platform.logistics.utils.IOUtils;
import com.fy56.platform.logistics.utils.MD5Util;
import com.fy56.platform.logistics.utils.StaticUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zeus.base.privilege.model.TbCompany;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.fy56.platform.logistics.utils.HttpUtil.setHeader;

/**
 * 项目Service实现
 * @author wxm
 * @date 2019-5-16
 */
@Service
public class DeliverGoodsWebSetServiceImpl implements IDeliverGoodsWebSetService {


    @Autowired
    private DeliverGoodsWebSetMapper deliverGoodsWebSetMapper;


    @Override
    public ResultModel insert(Company model, String companyCode, String childCodes, String loginName) {

        if (model != null){

            //获取从认证中心获取所有子公司（网点）信息
            List<TbCompany> subCompanyList =null;
            //20200414 lml 改成http方式请求腾云获取公司信息
            try{
                Map<String, String> paramsNew = Maps.newHashMap();
                paramsNew.put("companyCode",model.getCode());
                paramsNew.put("passWord", MD5Util.getMD5Code(model.getTenantPass()));
                paramsNew.put("parentId",model.getId()+"");
                String url= IOUtils.getConfigParam("restSearchURL", "url.properties");
                if(url==null||url.length()==0){
                    url="http://tengyun.feiyang56.cn:60002/privilege-restful-api";
                }
                String result = HttpClientUtils.post( url+"/privilegeManager/selectByParentId", paramsNew, setHeader(), 20000, 20000);
                if(result!=null){
                    JSONObject j = JSON.parseObject(result);
                    String  object=j.get("object")+"";
                    subCompanyList= JSON.parseArray(object, TbCompany.class);
                }
            }catch (Exception e){
                System.out.println(e);
            }

            List<String> companyCodes = Arrays.asList(companyCode);

            List<DeliverGoodsWeb> dgWebs = new ArrayList<>();
            String[] childCodeArray = childCodes.split(",");
            List<String> childWebNames = new ArrayList<String>();
            List<String> isDeletedChildWebCompanyCodes = new ArrayList<String>();
            //构筑网点信息（名称，地址等
            if (CollectionUtils.isNotEmpty(subCompanyList)) {
                for (TbCompany web : subCompanyList) {
                    if (web.getDisplayFlag() != 1) {
                        for (String childCode : childCodeArray){
                            //从所有子网点中，找到已经设置为发货网点的子网点
                            if (web.getCompanyCode().equals(childCode)){
                                childWebNames.add(web.getCompanyNameAlias() != null ? web.getCompanyNameAlias() : web.getCompanyName());
                                DeliverGoodsWeb dgWeb = tbCompanyToDeliverGoodsWeb(web, companyCode, true, "", loginName);
                                dgWebs.add(dgWeb);
                                break;
                            }
                        }
                    }
                }
                //主公司
                DeliverGoodsWeb dgWeb = companyToDeliverGoodsWeb(model, "", false, StringUtils.join(childWebNames, "|"), loginName);
                //从数据库查出要设置的发货网点，和提交数据进行比较，
                // 新增的插入，以前有的更新（以前设置过，这次又再次设置，则更新数据），
                // 取消的删除（以前设置过，这次没有设置，则删除数据）
                DeliverGoodsWeb param = new DeliverGoodsWeb();
                param.setCompanyCode(dgWeb.getCompanyCode());
                param.setDeleteFlag(0);
                param.setIsChildWeb(false);
                //查出主公司网点
                List<DeliverGoodsWeb> resList = deliverGoodsWebSetMapper.select(param);

                if (resList != null && resList.size() > 0){
                    dgWeb.setId(resList.get(0).getId());
                    DeliverGoodsWeb childParam = new DeliverGoodsWeb();
                    childParam.setParentCode(dgWeb.getCompanyCode());
                    childParam.setDeleteFlag(0);
                    //查出主公司下的子网点
                    List<DeliverGoodsWeb> resChildList = deliverGoodsWebSetMapper.select(childParam);
                    for (DeliverGoodsWeb resChild : resChildList){
                        boolean flag = false;
                        for (DeliverGoodsWeb w : dgWebs){
                            if (w.getCompanyCode().equals(resChild.getCompanyCode())){
                                w.setId(resChild.getId());
                                flag = true;
                                break;
                            }
                        }
                        if (false == flag){
                            isDeletedChildWebCompanyCodes.add(resChild.getCompanyCode());
                        }
                    }
                }
                //有删除的子网点，则进行删除操作
                if (isDeletedChildWebCompanyCodes.size() > 0) {
                    Map deleteMap = new HashMap();
                    deleteMap.put("companyCodes", isDeletedChildWebCompanyCodes);
                    deleteMap.put("updateLoginName", loginName);
                    deliverGoodsWebSetMapper.deleteByCompanyCodes(deleteMap);
                }
                //将设置好的公司和发货网点，保存到本地数据库
                dgWebs.add(dgWeb);
                deliverGoodsWebSetMapper.insertOnDuplicate(dgWebs);
                return ResultModel.ok();
            }
            return ResultModel.ok("设置失败，未找到代码为"+companyCode+"的公司的下属公司网点");
        }
        return ResultModel.ok("设置失败，未找到代码为"+companyCode+"的公司网点");
    }

    /**
     * 获取公司网点及子网点
     *
     * @param companyCode
     * @return
     */
    @Override
    public ResultModel getWeb(Company model, String companyCode) {

        Map res = new HashMap();

        //初始化返回值
        List<Company> list = Lists.newArrayList();

        if (model != null){
            //获取从认证中心获取所有子公司信息
            List<TbCompany> subCompanyList = null;
    //20200414 lml 改成http方式请求腾云获取公司信息
            try{
                Map<String, String> paramsNew = Maps.newHashMap();
                paramsNew.put("companyCode",model.getCode());
                paramsNew.put("passWord", MD5Util.getMD5Code(model.getTenantPass()));
                paramsNew.put("parentId",model.getId()+"");
                String url=StaticUtil.restSearchURL;
                if(url==null||url.length()==0){
                   url="http://tengyun.feiyang56.cn:60002/privilege-restful-api";
                }
                String result = HttpClientUtils.post( url+"/privilegeManager/selectByParentId", paramsNew, setHeader(), 20000, 20000);
                if(result!=null){
                    JSONObject j = JSON.parseObject(result);
                    String object = j.get("object").toString();
                    subCompanyList= JSON.parseArray(object, TbCompany.class);
                }
            }catch (Exception e){
                System.out.println(e);
            }
            //构筑网点信息（名称，地址等
            if (CollectionUtils.isNotEmpty(subCompanyList)) {

                //从本地数据库，获取该公司下的发货网点
                DeliverGoodsWeb childParam = new DeliverGoodsWeb();
                childParam.setParentCode(companyCode);
                childParam.setDeleteFlag(0);
                List<DeliverGoodsWeb> dgWebs = deliverGoodsWebSetMapper.select(childParam);

                Company company = null;
                for (TbCompany web : subCompanyList) {
//                    //[判断]不显示-发货网点<0否,1是>
//                    if (web.getDisplayFlag() != 1) {
//                    }
                    company = new Company();
                    company.setCode(web.getCompanyCode());
                    company.setName(web.getCompanyNameAlias() != null ? web.getCompanyNameAlias() : web.getCompanyName());
                    company.setAddress(web.getAddressMap() != null ? web.getAddressMap() : web.getAddress());
                    company.setPhone(web.getPhone());
                    //该子网点是否设置成了发货网点（0：否，1：是）
                    company.setUseFlag(0);
                    for (DeliverGoodsWeb dgWeb : dgWebs){
                        //判断该子网点是否设置了可显示的发货网点（用于微信小程序显示）
                        if (web.getCompanyCode().equals(dgWeb.getCompanyCode())){
                            company.setUseFlag(1);
                        }
                    }
                    list.add(company);

                }
            }
        }
        res.put("web", model);
        res.put("childWeb", list);
        return ResultModel.ok(res);
    }

    /**
     * 查询发货网点
     * @param web
     * @return
     */
    @Override
    public ResultModel select(DeliverGoodsWeb web) {
        List<DeliverGoodsWeb> dgWebs = deliverGoodsWebSetMapper.select(web);
        return ResultModel.ok(dgWebs);
    }

    /**
     * 删除
     *
     * @param companyCodes  公司码
     * @return
     */
    @Override
    public ResultModel deleteByCompanyCodes(String companyCodes, String loginName) {
        List list = Arrays.asList(companyCodes.split(","));
        Map map = new HashMap();
        map.put("companyCodes", list);
        map.put("updateLoginName", loginName);
        deliverGoodsWebSetMapper.deleteByCompanyCodes(map);
        deliverGoodsWebSetMapper.deleteByParentCodes(map);
        return ResultModel.ok("删除成功");
    }

    public DeliverGoodsWeb tbCompanyToDeliverGoodsWeb(TbCompany tbCompany, String parentCode, boolean isChildWeb, String childWebNames, String loginName){
        DeliverGoodsWeb deliverGoodsWeb = new DeliverGoodsWeb(
                tbCompany.getCompanyId(),
                tbCompany.getApplicationIds(),
                tbCompany.getApplicationNames(),
                tbCompany.getApplicationNamesHide(),
                tbCompany.getCompanyCode(),
                tbCompany.getCompanyName(),
                tbCompany.getParent() != null ? tbCompany.getParent().getCompanyId() : null,
                tbCompany.getParentIds(),
                tbCompany.getAddress(),
                tbCompany.getZipCode(),
                tbCompany.getLinkMan(),
                tbCompany.getPhone(),
                tbCompany.getFax(),
                tbCompany.getEmail(),
                tbCompany.getTopCompanyId(),
                tbCompany.getSysData(),
                tbCompany.getAdministrativeDivision() != null ? tbCompany.getAdministrativeDivision().getAdministrativeDivisionId() : null,
                tbCompany.getAddressMap(),
                tbCompany.getAddressDetail(),
                tbCompany.getLongitude(),
                tbCompany.getLatitude(),
                tbCompany.getWebUrl(),
                tbCompany.getActivationFlag(),
                tbCompany.getCompanyNameAlias(),
                tbCompany.getF6OrganizationCode(),
                tbCompany.getF6AccountSet(),
                tbCompany.getAuditFlag(),
                tbCompany.getAuditUser() != null ? tbCompany.getAuditUser().getUserId() : null,
                tbCompany.getAuditTime(),
                tbCompany.getAuditMessage(),
                parentCode,
                isChildWeb,
                childWebNames,
                loginName,
                loginName);
        return deliverGoodsWeb;
    }


    public DeliverGoodsWeb companyToDeliverGoodsWeb(Company company, String parentCode, boolean isChildWeb, String childWebNames, String loginName){
        DeliverGoodsWeb deliverGoodsWeb = new DeliverGoodsWeb(
                Integer.parseInt(company.getId().toString()),
                null,
                null,
                null,
                company.getCode(),
                company.getName(),
                null,
                null,
                company.getAddress(),
                null,
                null,
                company.getPhone(),
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                company.getLongitude(),
                company.getLatitude(),
                null,
                null,
                null,
                company.getF6OrganizationCode(),
                company.getF6AccountSet(),
                null,
                null,
                null,
                null,
                parentCode,
                isChildWeb,
                childWebNames,
                loginName,
                loginName);
        return deliverGoodsWeb;
    }

    @Override
    public DeliverGoodsWeb selectByPrimaryKey(Long id) {
        return null;
    }

    @Override
    public DeliverGoodsWeb get(DeliverGoodsWeb entity) {
        return null;
    }

    @Override
    public ResultModel insert(DeliverGoodsWeb entity) {
        return null;
    }

    @Override
    public ResultModel insertSelective(DeliverGoodsWeb entity) {
        return null;
    }

    @Override
    public ResultModel update(DeliverGoodsWeb entity) {
        return null;
    }

    @Override
    public ResultModel updateSelective(DeliverGoodsWeb entity) {
        return null;
    }

    @Override
    public ResultModel delete(Long id) {
        return null;
    }

    @Override
    public ResultModel delete(DeliverGoodsWeb entity) {
        return null;
    }

    @Override
    public List<DeliverGoodsWeb> findList(DeliverGoodsWeb deliverGoodsWeb) {
        return null;
    }
}
